package com.hup.winHolderService.view;

import com.hup.utils.commons.hardware.HRobotJni;
import com.hup.utils.commons.hardware.ScreenUtil;
import com.hup.utils.commons.start.LookThemeUtil;

import javax.swing.*;
import java.lang.ref.WeakReference;

/**
 * 解除静音窗口:muteAndLock后登陆系统时,方便用户解除静音
 *
 * @author hugan
 * @date 2020/12/15
 */
public class NotMutedFrame extends JFrame {
    private static WeakReference<NotMutedFrame> instance = null;

    /**
     * @param isMute true-静音并显示窗口;false-取消静音并关闭窗口
     */
    public static void setMute(boolean isMute) {
        HRobotJni.setMute(isMute);

        NotMutedFrame frame;
        if (instance == null || (frame = instance.get()) == null) {
            if (!isMute) return;
            instance = new WeakReference<>(frame = new NotMutedFrame());
        }
        if (isMute) {
            frame.setVisible(true);
        } else {
            frame.dispose();
        }
    }

    private NotMutedFrame() {
        super("系统已静音");

        NotMutedForm form = new NotMutedForm();
        setContentPane(form.root);
        LookThemeUtil.initFrameSize(this, 300, 100);
        setLocation((ScreenUtil.getScreenSize().width - getWidth()) / 2, 0);
        setAlwaysOnTop(true);

        initListener(form);
    }

    private void initListener(NotMutedForm form) {
        form.btnNotMute.addActionListener(e -> {
            HRobotJni.setMute(false);
            dispose();
        });
        form.btnDispose.addActionListener(e -> dispose());
    }

    @Override
    public void dispose() {
        super.dispose();
        instance.clear();
        instance = null;
    }
}
